package com.lebang.controller.sys.cences;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lebang.common.Login;
import com.lebang.configuration.datasource.DataSource;
import com.lebang.domain.CencesAppstoreRegister;
import com.lebang.example.CencesAppstoreRegisterExample;
import com.lebang.model.MyConfig;
import com.lebang.service.cences.CencesAppstoreRegisterService;
import com.lebang.service.cences.CencesBrandRegisterService;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 渠道注册率统计
 *
 * @author xwj
 * @date 2020-04-27
 */
@Controller
@RequestMapping("/sys/cences/cencesbrandregister")
public class CencesBrandRegisterController {
    @Autowired
    private CencesBrandRegisterService baseService;
    @Autowired
    private CencesAppstoreRegisterService cencesAppstoreRegisterService;

    @Login
    @GetMapping("/list")
    @DataSource("commonDB")
    public String list(Model model) {

        Integer time = cencesAppstoreRegisterService.selectOneByLimit(MyConfig.getEnv());
        CencesAppstoreRegisterExample example = new CencesAppstoreRegisterExample();
        if(time!=null){
            example.createCriteria().andTimeEqualTo(time).andAppIdEqualTo(MyConfig.getEnv());
        }else{
            example.createCriteria().andAppIdEqualTo(MyConfig.getEnv());
        }
        List<CencesAppstoreRegister> list = cencesAppstoreRegisterService.selectByExample(example);

            JSONArray jsonArray = new JSONArray();

            list.parallelStream().forEach(t -> {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("device",t.getDeviceNum());
                jsonObject.put("appStore",t.getAppStore());
                jsonArray.add(jsonObject);
            });

        jsonArray.sort(Comparator.comparing(obj -> ((JSONObject) obj).getInteger("device")).reversed());
        model.addAttribute("newAppStoreList",jsonArray);
        return "/cencesbrandregister/list";
    }

    /**
     * @param page  页数
     * @param limit 条数
     * @param star  开始日期
     * @param end   结束日期
     * @return 返回数据
     */
    @PostMapping("/page")
    @ResponseBody
    @Login
    @DataSource("commonDB")
    public HashMap newList(Long page, Integer limit, Integer star, Integer end) {
        CencesAppstoreRegisterExample example = new CencesAppstoreRegisterExample();
        example.setOffset((page - 1) * limit);
        example.setLimit(limit);
        example.setOrderByClause("time desc");
        CencesAppstoreRegisterExample.Criteria criteria = example.createCriteria();
        criteria.andAppIdEqualTo(MyConfig.getEnv());
        List<Integer> timeList = cencesAppstoreRegisterService.selectByLimit((page - 1) * limit, limit,MyConfig.getEnv());
        Long count = cencesAppstoreRegisterService.countAll(MyConfig.getEnv());
        if (timeList != null) {
            star = timeList.get(timeList.size() - 1);
            end = timeList.get(0);
        }
        if (star != null && end != null) {
            criteria.andTimeBetween(star, end);
        }
        example.setOffset(null);
        example.setLimit(null);
        List<CencesAppstoreRegister> list = cencesAppstoreRegisterService.selectByExample(example);
        Map<Integer, List<CencesAppstoreRegister>> map1 = list.parallelStream().collect(Collectors.groupingBy(CencesAppstoreRegister::getTime));
        JSONArray jsonArray = new JSONArray();
        map1.forEach((k, v) -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("time", k);
            v.parallelStream().forEach(t -> {
                jsonObject.put(t.getAppStore(), "新增:" + t.getDeviceNum() + "<br/>注册:" + t.getRegister() + "<br/>注册率:" + getRate(t.getRegister(), t.getDeviceNum()) + "%");
            });
            jsonArray.add(jsonObject);
        });
        jsonArray.sort(Comparator.comparing(obj -> ((JSONObject) obj).getInteger("time")).reversed());

        HashMap map = new HashMap(1);
        map.put("count", count);
        map.put("code", 0);

        map.put("data", jsonArray);
        return map;
    }

    private BigDecimal getRate(Integer register, Integer deviceNum) {

        if (deviceNum == 0) {
            return BigDecimal.ZERO;
        }

        return BigDecimal.valueOf(register).multiply(BigDecimal.valueOf(100)).divide(BigDecimal.valueOf(deviceNum), 2, BigDecimal.ROUND_DOWN);

    }


    @Login
    @PostMapping("/delete")
    @ResponseBody
    @DataSource("commonDB")
    public JsonData delete(Integer id) {
        baseService.deleteByTime(baseService.selectById(id).getTime());
        return Callback.success("success", "删除成功");
    }


    /**
     * 统计指定日期渠道活跃人数
     *
     * @param date 日期
     * @return 返回结果
     */
    @Login
    @PostMapping("/lastCheck")
    @ResponseBody
    public String cen(String date) {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate end = LocalDate.parse(date, fmt);
        baseService.starDataInit(LocalDateTime.of(end.plusDays(1), LocalTime.MIN));
        return "success";
    }


}
